<template>
  <div class="app-container">
    <el-row :gutter="20" style="height:calc(100% - 40px);">
      <!-- 四个播放器 -->
      <el-col :span="4" style="height: 500px; overflow-y:auto;">
          <div class="head-container">
              <el-tree-select
                  v-model="selectedUnitId"
                  :data="UnitOptions"
                  default-expand-all
                  :props="{ value: 'id', label: 'label', children: 'children' }"
                  value-key="id"
                  placeholder="选择单位"
                  check-strictly
                  @node-click="handleNodeClickUnit"
              />
          </div>
          <el-divider />
          <div class="head-container" v-loading="loadingdeptOptions">
                  <el-tree :data="deptOptions" 
                  :props="{ value: 'id', label: 'label', children: 'children' }"
                  :expand-on-click-node="false" 
                  :filter-node-method="filterNode" 
                  ref="deptTreeRef" node-key="id"
                  highlight-current
                  @node-click="handleNodeClick" />
          </div>
      </el-col>
      <el-col :span="17">
          <el-row :gutter="1"  style="height:100%">
              <el-col :span="12" style="height:50%;margin-bottom:1px;"
              :style="getPlayerStyle(0)" @click="click(0)" id="Player0">
                  <easy-player 
                      ref="vVideoPlayerRef0" 
                      live 
                      muted 
                      autoplay
                      :video-url="videoUrlLists[0]">
                  </easy-player>
              </el-col>
              <el-col :span="12" style="height:50%;margin-bottom:1px;" id="Player1"
              :style="getPlayerStyle(1)" @click="click(1)">
                  <easy-player 
                      ref="vVideoPlayerRef1" 
                      live 
                      muted 
                      autoplay
                      :video-url="videoUrlLists[1]">
                  </easy-player>
              </el-col>
              <el-col :span="12" style="height:50%;margin-bottom:1px;" id="Player2"
              :style="getPlayerStyle(2)" @click="click(2)">
                  <easy-player 
                      ref="vVideoPlayerRef2" 
                      live 
                      muted 
                      autoplay
                      :video-url="videoUrlLists[2]">
                  </easy-player>
              </el-col>
              <el-col :span="12" style="height:50%;margin-bottom:1px;" id="Player3"
              :style="getPlayerStyle(3)" @click="click(3)">
                  <easy-player 
                      ref="vVideoPlayerRef3" 
                      live 
                      muted 
                      autoplay
                      :video-url="videoUrlLists[3]">
                  </easy-player>
              </el-col>
          </el-row>
      </el-col>
      <!-- 操作区 -->
      <el-col :span="3">
          <el-col :span="24">
              <el-button @click="closevideo" class="mb-4">关闭监控</el-button>
          </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
const {proxy} = getCurrentInstance();
  import { ElMessage } from 'element-plus'
  import { getunitDeviceChannelTreeType } from "@/api/ParameterSetting/Device";
  import { getChannelUrl ,} from "@/api/videoApi/videoApi";
  import {deptTreeSelectPost} from "@/api/system/user.js";
  const loading = ref(false)

  // 视频列表
  const videoUrlLists = ref([]);
  const params = ref({
    unitId:'',
    bigType: "12309检察服务中心"
  })
  const vVideoPlayerRef0 = ref()
  const vVideoPlayerRef1 = ref()
  const vVideoPlayerRef2 = ref()
  const vVideoPlayerRef3 = ref()

  const selectedUnitId = ref('')
  const UnitOptions = ref([])
  const deptOptions = ref([])
  const loadingdeptOptions = ref(false)

  onMounted(() => {
    getDeptTree()
  })
  function getDeptTree() {
      loading.value = true
      deptTreeSelectPost({isUnit: true}).then(res => {
        UnitOptions.value  = res.data
        loading.value = false
      });
    }
  
  // 记录当前选中的播放器
  const activePlayer = ref(0);

  // 点击播放器改变样式
  const click = (index) => {
      activePlayer.value = index
  }
  // 获取播放器的样式
  const getPlayerStyle = (index) => {
    return activePlayer.value === index
      ? { border: '2px solid red' }  // 选中的播放器边框为红色
      : {};
  }

  function filterNode(value, data){
    if (!value) return true;
    return data.deptName.indexOf(value) !== -1;
  }
  
  // 播放器引用
  const vVideoPlayerRefs = [
    ref(null), ref(null), ref(null), ref(null)
  ];

  // 关闭监控功能
  const closevideo = () => {
      console.log(activePlayer.value)
      // 关闭当前选中的播放器
      let player = null
      switch (activePlayer.value) {
      case 0:
          player = vVideoPlayerRef0.value.getVueInstance();
          player.destroyPlayer();
          break;
      case 1:
          player = vVideoPlayerRef1.value.getVueInstance();
          player.destroyPlayer();
          break;
      case 2:
          player = vVideoPlayerRef2.value.getVueInstance();
          player.destroyPlayer();
          break;
      case 3:
          player = vVideoPlayerRef3.value.getVueInstance();
          player.destroyPlayer();
          break;
      default:
        ElMessage.error('播放器索引无效');
    }
  }

  function handleNodeClickUnit(data){
    getunitDeviceChannelTreeList(data.id)
  }
  function handleNodeClick(data) {
    // 处理节点单击事件
      if(data.channelcode){
        const playerQuery = {
          deviceId:data.channelcode,
          channel:data.channels,
          monitorServerId:data.monitorserverId,
        }
      getChannelUrl(playerQuery).then(res => {
          var mergeUrl = res.data.prefix + res.data.EasyDarwin.Body.URL
          videoUrlLists.value[activePlayer.value] = mergeUrl
          activePlayer.value = (activePlayer.value + 1) % 4;
      })
    }
  }
  function getunitDeviceChannelTreeList(UnitId) {
    loadingdeptOptions.value = true
    deptOptions.value = []
    params.value.unitId = UnitId
   
    getunitDeviceChannelTreeType(params.value).then(res => {
      // 递归转换 roomTypes 中的结构
      const transformRoomTypes = (roomTypes) => {
        return roomTypes.map(room => {
          // 保留原有的 id 和 label，如果存在的话
          const transformedRoom = {
            ...room,
            label: room.label || room.roomname,  // 仅当 label 不存在时才使用 roomname
            id: room.id || room.roomId          // 仅当 id 不存在时才使用 roomId
          };

          if (room.baseMonitorChannels) {
            // 将 baseMonitorChannels 改为 children，并处理其中的字段
            transformedRoom.children = room.baseMonitorChannels.map(channel => {
              return {
                ...channel,
                label: channel.label || channel.channelname, // 仅当 label 不存在时才使用 channelname
                id: channel.id || channel.channelcode       // 仅当 id 不存在时才使用 channelcode
              };
            });
            delete transformedRoom.baseMonitorChannels; // 删除 baseMonitorChannels 字段
          }
          // 递归处理嵌套的 children（即 room 下的子房间）
          if (room.children && room.children.length > 0) {
            transformedRoom.children = transformRoomTypes(room.children);
          }
          return transformedRoom;
        });
      };
      if (res.data && Array.isArray(res.data) && res.data[0] && res.data[0].roomTypes) {
          var roomTypesdata = transformRoomTypes(res.data[0].roomTypes);
      } else {
          ElMessage.error('当前单位无监控节点');
          loadingdeptOptions.value = false
      }
      // 处理 videoTypes
      if (res.data && res.data[0] && res.data[0].videoTypes) {
          let videoTypesdata = res.data[0].videoTypes;
          videoTypesdata.forEach(videoType => {
              videoType.children.forEach(channel => {
                  channel.label = channel.label || channel.channelname; // 使用 channelname 作为备选
                  channel.id = channel.monitorchannelsId || channel.channelcode; // 使用 channelcode 作为备选
              });
          });
          deptOptions.value = [
            ...roomTypesdata,
            ...videoTypesdata
          ];
      } else {
          console.error("videoTypes data is missing in the response:", res.data);
      }
      loadingdeptOptions.value = false
    });
  }
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - 84px);
}

#video-player-box {
  height: 500px;
}
.operation-box {
  margin-top: 10px;
}
.player-content{height: 100%;}
</style>
